import { initExecute } from '../../../_resource/common/utils/index.js';
import { _ProPager } from '../../../config.js';
export default (hook, { Pagination }) => {
	return {
		isJiess: true,
		name: 'ProPager',
		setup({ midder }) {
			const { $ref, $watchEffect } = hook.$m;
			const { pager, proxy, table } = midder;
			const showSizeChangerRef = $ref();
			const showQuickJumperRef = $ref();
			// ====================================================
			const cnf = initExecute.call(this)(_ProPager, [midder], {});
			const { showSizeChanger = true, showQuickJumper = true, ...pagerProps } = cnf;

			// 采用同步数据更新方案，初始无参数值，可以触发观察器
			// 在观察到数据变化后，会在第一时间触发更新，而此刻代理值还未发生变化，
			// 因此使用第一时间提供的变化参数作为变动值，保障同步数据的更新
			$watchEffect((value = proxy.pageSize) => {
				pager.values.pageSize = value;
			}, { model: 'sync' });
			$watchEffect(() => {
				pager.values.page = proxy.currentPage
			}, { model: 'sync' });
			$watchEffect(() => (showSizeChangerRef.value = proxy.showSizeChanger || showSizeChanger));
			$watchEffect(() => (showQuickJumperRef.value = proxy.showQuickJumper || showQuickJumper));
			// 重置当前页和每页数量
			pager.reset = () => {
				// 重置为在utils中采集到的初始默认值
				proxy.pageSize = pager.defaultPageSize || 10;
				proxy.currentPage = pager.defaultPage || 1;
			}
			this.add({
				is: Pagination,
				showSizeChanger: { $proxy: showSizeChangerRef },
				showQuickJumper: { $proxy: showQuickJumperRef },
				pageSizeOptions: { $proxy: proxy, field: 'pageSizes' },
				current: { $proxy: proxy, field: 'currentPage' },
				pageSize: { $proxy: proxy, field: 'pageSize' },
				total: { $proxy: proxy, field: 'total' },
				showTotal: (total) => `共 ${total} 条`,
				onChange(page, pageSize) {
					pager.values = { page, pageSize };
					table.reload();
				},
				...pagerProps,
				...pager.pagerProps,
			});
		},
	};
}